package com.google.code.greenplate;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mobi.greenplate.client.connect.ConnectionContext;
import mobi.greenplate.client.domain.Address;
import mobi.greenplate.client.service.AddressService;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ShareRideOffer extends ListActivity {
	
	private ListView mListView;	
	private ProgressDialog mProgressDialog = null;
	private ArrayList<Ride> mALRides = null;
	private RideAdapter mAdapter;
		
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_ride_offer);
        mListView = getListView();
        setListeners();
        mALRides = new ArrayList<Ride>();
        mAdapter = new RideAdapter(this, R.layout.share_ride_offer_listitem, mALRides);
        setListAdapter(this.mAdapter);
        
        Thread thread = new Thread() {
        	public void run() {
        		getRides();
        	}
        };     
        thread.start();
        mProgressDialog = ProgressDialog.show(this, "Please wait...", "Retrieving data...", true);
    }
    
    public void setListeners() {
    	mListView.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, 
    				int position, long id) {
    			// When clicked, show a toast with the TextView text
    			//Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
                
    			Intent intent = new Intent(ShareRideOffer.this, ShareRideOfferDetails.class);
    			setIntentExtras(intent, position);
                startActivity(intent);
    		}
    	});
    }
    
    public void setIntentExtras(Intent intent, int position) {
    	Ride r = mALRides.get(position);
    	intent.putExtra("driver", r.getUser());
    	intent.putExtra("departTime", r.getDepartTime());
    	intent.putExtra("fromCity", r.getFromCity());
    	intent.putExtra("toCity", r.getToCity());
    }
    
    public static ConnectionContext localhostConnectionContext(){
        final ConnectionContext cc = new ConnectionContext("192.168.1.100", 8080, "testuser", "testuser");
        return cc;
    }
    
    private AddressService getAddressService(){
        return new AddressService(localhostConnectionContext());
    }
    
    private class RideAdapter extends ArrayAdapter<Ride> {
    	
		private ArrayList<Ride> items;
    	private int[] colors = new int[] {0x30ffffff, 0x30808080};    	
    	
    	public RideAdapter(Activity context, int textViewResourceId, ArrayList<Ride> items) {
    		super(context, textViewResourceId, items);
    		this.items = items;
    	}
    	
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View v = convertView;
    		if (v == null) {
    			LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			v = vi.inflate(R.layout.share_ride_offer_listitem, null);  			
    		}
    		Ride r = items.get(position);
    		if (r != null) {
    			TextView t1 = (TextView) v.findViewById(R.id.text1);
    			TextView t2 = (TextView) v.findViewById(R.id.text2);
    			TextView t3 = (TextView) v.findViewById(R.id.text3);
    			if (t1 != null) {
    				t1.setText(r.getUser() + " - " + r.getDepartTime());
    			}
    			if (t2 != null) {
    				t2.setText("from: " + r.getFromCity());
    			}
    			if (t3 != null) {
    				t3.setText("to: " + r.getToCity());
    			}
    		}
    		int colorPos = position % colors.length;
			v.setBackgroundColor(colors[colorPos]);
    		return v;
    	}   	
    }
    
    private void getRides() {
    	try {
    		mALRides = new ArrayList<Ride>();
    		Ride r1 = new Ride();
    		r1.setUser("david");
    		r1.setDepartTime("3:30pm");
    		r1.setFromCity("Mountain View, CA");
    		r1.setToCity("San Francisco, CA");
    		Ride r2 = new Ride();
    		r2.setUser("john");    		
    		r2.setDepartTime("4:30pm");
    		r2.setFromCity("Sunnyvale, CA");
    		r2.setToCity("San Jose, CA");
    		Ride r3 = new Ride();
    		r3.setUser("sue");
    		r3.setDepartTime("5:15pm");
    		r3.setFromCity("San Mateo, CA");
    		r3.setToCity("Mountain View, CA");
    		mALRides.add(r1);
    		mALRides.add(r2);
    		mALRides.add(r3);
    		//Thread.sleep(1000);
    		
    		final List<Address> addressList = getAddressService().findAll(0, 10);
            //final Address address = addressList.get(0);
            
            for (Address a : addressList) {
            	Ride r = new Ride();
            	r.setUser(a.getStreet());
            	r.setDepartTime(a.getCity());
            	r.setFromCity(a.getState());
            	r.setToCity(a.getZip());
            	mALRides.add(r);
            }   		
    		
    		Log.i("ARRAYLIST", "" + mALRides.size());	
    	} catch (Exception e) {
    		Log.e("BACKGROUND_PROC", e.getMessage());
    	}
    	runOnUiThread(updateAdapter);
    }
    
    private Runnable updateAdapter = new Runnable() {
	    	//@Override
	    	public void run() {
	    		if (mALRides != null && mALRides.size() > 0) {
	    			mAdapter.notifyDataSetChanged();
	    			for (int i = 0; i < mALRides.size(); i++) {
	    				mAdapter.add(mALRides.get(i));
	    			}
	    		}
	    		mProgressDialog.dismiss();
	    		mAdapter.notifyDataSetChanged();	
	    	}
	    };
	    
	private void parseXMLFile() {
		try {
			InputSource is = new InputSource(getResources().openRawResource(R.raw.transport));
			// Create the factory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// Create a parser
			SAXParser parser = factory.newSAXParser();
			// Create the reader(scanner)
			XMLReader xmlreader = parser.getXMLReader();
			// Instantiate our handler
			RideOfferFeedHandler offerHandler = new RideOfferFeedHandler();
			
			// Assign our handler
			xmlreader.setContentHandler(offerHandler);
			// Perform the synchronous parse
			xmlreader.parse(is);
			// Should be done... let's display our results
			//tvData.setText(offerHandler.getResults());			
		} catch (Exception e) {
			Log.e("BACKGROUND_PROC", e.getMessage());
		}		
	}
	

	
	
}